/*
 * DocumentRouter.java
 *
 * Created on July 15, 2006, 2:11 PM
 *
 * (C) R. Alexander Milowski alex@milowski.com
 */

package org.infoset.xml.util;

import java.util.HashMap;
import java.util.Map;
import org.infoset.xml.Element;
import org.infoset.xml.Item;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.Name;
import org.infoset.xml.XMLException;

/**
 *
 * @author R. Alexander Milowski
 */
public class DocumentRouter extends ItemQueue {
   
   Map<Name,ItemDestination> routes;
   ItemDestination defaultRoute;
   ItemDestination currentRoute;
   
   /** Creates a new instance of DocumentRouter */
   public DocumentRouter() {
      routes = new HashMap<Name,ItemDestination>();
      currentRoute = null;
      defaultRoute = null;
   }
   
   public void addRoute(Name name,ItemDestination dest) {
      if (name!=null) {
         routes.put(name,dest);
      } else {
         defaultRoute = dest;
      }
   }
   
   public void send(Item item) 
      throws XMLException
   {
      if (currentRoute==null) {
         super.send(item);
         if (item.getType()==Item.ItemType.ElementItem) {
            Name name = ((Element)item).getName();
            currentRoute = routes.get(name);
            if (currentRoute==null) {
               currentRoute = defaultRoute;
            }
            if (currentRoute==null) {
               throw new XMLException("No route matches "+name);
            }
            replay(currentRoute);
         }
      } else {
         currentRoute.send(item);
         if (item.getType()==Item.ItemType.DocumentEndItem) {
            currentRoute = null;
         }
      }
   }
   
}
